<template>
  <div class="remote-schedule-container">
    <a-spin :spinning="loading">
      <a-form layout="vertical" class="operate-page-form" :model="formState" @validateFields="handleOk" ref="formRef">
        <div class="operate-page-content">
          <div class='blue-line mb-13'>{{ $t('other.makeMsg') }}</div>
          <MakeDetailTable ref="makeDetailTable" :tableData="detailTableData" @onSelectChange="onSelectChange" :lineList="lineList" :personList="personList"  :operateType="operateType" :stationList="stationList"/>
          <div class="mt-20 mb-8"> <span class="text-red">*</span>{{ $t('other.prodSite') }}：</div>
          <a-row :gutter="40">
            <a-col :span="20">
              <div class="tags-box mh-50" v-if="operateType == 'details' ">
                <a-tag  @close="delStationTag(item)" v-for="(item) in stationList"  :key="item.key" class="mb-10 ft-size14">{{ item.title }}</a-tag>
              </div>
              <div class="tags-box mh-50" v-else>
                <a-tag @click="addStation()">
                  <span class="text-primary">
                    <plus-outlined class="mr-5" />{{ $t('common.add') }}
                  </span>
                </a-tag>
                <a-tag closable @close="delStationTag(item)" v-for="(item) in stationList"  :key="item.key" class="mb-10 ft-size14">{{ item.title }}</a-tag>
              </div>
            </a-col>
          </a-row>
          <div class="mt-20 mb-8"> <span class="text-red">*</span>{{ $t('other.pordUser') }}：</div>
          <a-row :gutter="40">
            <a-col :span="20">
              <div class="tags-box mh-50" v-if="operateType == 'details'">
                <a-tag @close="delPersonTag(item)" v-for="(item) in personList"  :key="item.key" class="mb-10 ft-size14">{{ item.title }}</a-tag>
              </div>
              <div class="tags-box mh-50" v-else>
                <a-tag @click="addPerson()">
                  <span class="text-primary">
                    <plus-outlined class="mr-5" />{{ $t('common.add') }}
                  </span>
                </a-tag>
                <a-tag closable @close="delPersonTag(item)" v-for="(item) in personList"  :key="item.key"  class="mb-10 ft-size14">{{ item.title }}</a-tag>
              </div>
            </a-col>
          </a-row>
          <div class="mt-20 mb-8"> {{ $t('other.annex') }}：</div>
          <a-row class=" mh-55">
            <a-col :span="12" class="upload-list-box">
              <a-upload  v-model:file-list="fileList"  :headers="uploadHeadersToken"  :action="uplaodUrl" @change="handleImportExcel" :disabled="operateType == 'details'">
                <a-button ghost type="primary" v-if="operateType != 'details'">{{ $t('other.upload') }}</a-button>
              </a-upload>
            </a-col>
          </a-row>
          <div class="mt-20 mb-8 ">{{ $t('common.remark') }}：</div>
          <a-row>
            <a-col :span="12">
              <a-form-item name="remark">
                <a-textarea :placeholder="$t('common.pleaseInput')" v-model:value="formState.remark" :disabled="operateType == 'details'"></a-textarea>
              </a-form-item>
            </a-col>
          </a-row>
          <div class='blue-line mb-13 mt-10'>
            {{$t('hangManage.processInfo')}} <a-switch class="ml-8" v-model:checked="checkedProc" v-if="operateType != 'details'" />
          </div>
          <OperateProcList ref="operateProcList" :processInfoList="processInfoList"  :processList="processList" :checkedProc="checkedProc" :operateType="operateType" :version="version" />
        </div>
        <div class="operate-page-btns">
          <a-space v-if="operateType == 'add'">
            <a-button @click="closeTab" class="cancel">{{$t('common.cancel')}}</a-button>
            <a-button @click="handleOk(0)" class="cancel" >{{$t('common.save')}}{{ $t('other.asDraft') }}</a-button>
            <a-button @click="handleOk(1)" type="primary" class="confirm" >{{ $t('other.submitAppl') }}</a-button>
          </a-space>
          <a-space v-else-if="operateType == 'edit'">
            <a-button @click="closeTab" class="cancel">{{$t('common.cancel')}}</a-button>
            <a-button @click="handleOk(0)" class="cancel" v-if="statusValue == 0" >{{$t('common.save')}}{{ $t('other.asDraft') }}</a-button>
            <a-button @click="handleOk(1)" type="primary" class="confirm" >{{ $t('other.submitAppl') }}</a-button>
          </a-space>
          <a-space v-else>
            <a-button @click="returnBack" class="cancel">{{ $t('other.back') }}</a-button>
          </a-space>

        </div>
      </a-form>
    </a-spin>
    <AddStationModal ref="addStationModalRef" @ok="onAddStationOk" />
    <AddPersonModal ref="addPersonModalRef" @ok="onAddPersonOk" />
  </div>
</template>
<script setup >
import MakeDetailTable from './makeDetailTables.vue'
import OperateProcList from './operateProcList.vue'
import  AddPersonModal from './addPersonModal.vue'
import AddStationModal from './addStationModal.vue'
import { ref, computed, onMounted, nextTick } from 'vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import axios from '@/utils/request'
import { cloneDeep ,isEmpty} from 'lodash'
import { store } from '@/store'
import moment from 'moment'
import {getBaseUrl,getToken} from '@/utils'

import i18n from '@/locales/index' 
const { t } = i18n.global
let uploadHeadersToken = {
  Authorization: getToken()
}
let uplaodUrl = `${getBaseUrl(process.env.NODE_ENV)}/api/system/file/upload`

const route = useRoute()
const router = useRouter()
let recordInfo = ref({})
let loading = ref(false)
let operateType = ref('')
let checkedProc = ref(true)
let addStationModalRef = ref()
let addPersonModalRef = ref()
let personList = ref([])
let stationList = ref([])
let lineList = ref([])
let fileList = ref([])
let processList = ref([])
let processInfoList = ref([])
let version = ref('')
let statusValue = ref(0) // 0 草稿 1 待排产2 已排产3


const tabs = computed(() => {
  return store.state.setting.tabs
})
let detailTableData = ref([])
let formState = ref({})
const formRef = ref()
const makeDetailTable = ref()
const operateProcList = ref()
const staffList = ref([])
const staffGroupList = ref([])
const addStation = async () => {
  if (makeDetailTable.value.baseData.length>0 && !makeDetailTable.value.baseData[0].lineId){
    message.error(t('video.pleaseSelectWaterLine'))
    return
  }
  const res = await axios.postAction('/api/device/station/get-hangerLineId-by-station', {
    hangerLineIdList: [makeDetailTable.value.baseData[0].lineId]
  })
  if (res.success && !isEmpty(res.data)){
    addStationModalRef.value.open(res.data,stationList.value)
  }else{
    message.warning(t('other.waterLineDownNotStation'))
  }
}
const onSelectChange =() => {
  stationList.value = []
}

const addPerson = async () => {
  if (!isEmpty(staffList.value)){
    addPersonModalRef.value.open( staffList.value , staffGroupList.value ,personList.value)
  }else{
    message.warning(t('other.productStaffNotExist'))
  }
}
const onAddStationOk = (fileList) => {
  stationList.value = fileList
  // console.log(stationList.value,'onAddStationOk-----------')
  // dataSource.value[index].processPictureUrlList = fileList
}
const onAddPersonOk = (fileList) => {
  personList.value = fileList
  detailTableData.value[0]['userNum'] = personList.value.length
  detailTableData.value[0]['lineId'] = makeDetailTable.value.baseData[0].lineId
  // console.log(detailTableData.value)
  // console.log(personList.value,'personList------***---')
}

const delStationTag = (item) => {
  stationList.value= stationList.value.filter(i=>i.title != item.title)
}
const delPersonTag = (item) => {
  personList.value= personList.value.filter(i=>i.title != item.title)
}
const handleOk = async (status) => {
  loading.value = true
  try {
    // console.log(fileList.value) // 上传路径
    let fileTmp = cloneDeep(fileList.value)
    let urlList = []
    fileTmp && fileTmp.forEach(item=>{
      if (item.url){
        urlList.push(item.url)
      }else{
        urlList.push(item.response.data)
      }
    })
    recordInfo.value['urlList'] = urlList

    // console.log(recordInfo.value,'recordInfo.value submit---------------------------------------')
    const values = await formRef.value.validateFields()
    let params = queryParams(values)
    if (params.value.lineId == null || params.value.staffIds.length ===0  || params.value.stationNos.length ===0 ){
      message.error(t('other.mandatoryNull'))
      loading.value = false
      return
    }
    params.value.status = status;
    // console.log(params.value ,'params-----------------------------------')
    if (operateType.value === 'add'){
      const res = await axios.postAction('/api/mo/auto-roadmap/save', params.value)
      if (res.success) {
        message.success(res.msg || t('common.doSuccess'))
        closeTab(true)
      }
    }else if(operateType.value === 'edit'){
      const res = await axios.postAction('/api/mo/auto-roadmap/edit', params.value)
      if (res.success) {
        message.success(res.msg || t('common.doSuccess'))
        closeTab(true)
      }
    }
    loading.value = false
  } catch (err) {
    loading.value = false
  }
}
const returnBack = async (isSuccess) => {
  const tabList = cloneDeep(tabs.value)
  let changeTabs = tabList.filter((i) => {
    if (isSuccess) {
      return !['/makeManage/editSchedule/details', route.path].includes(i.path)
    } else {
      return i.path !== route.path
    }
  })
  await store.commit('updateState', { tabs: changeTabs })
  if (route.query.type == 'sch'){
    router.push({
      path: '/makeManage/autoScheduleOnline'
    })
  }else if (route.query.type == 'loc'){
    router.push({
      path: '/makeManage/autoSchLocal'
    })
  } else{
    router.push({
      path: '/makeManage/autoScheduleLocal'
    })
  }
}
const closeTab = async (isSuccess) => {
  // console.log(isSuccess)
  const tabList = cloneDeep(tabs.value)
  let changeTabs = tabList.filter((i) => {
    if (isSuccess) {
      return !['/makeManage/editSchedule', route.path].includes(i.path)
    } else {
      return i.path !== route.path
    }
  })
  await store.commit('updateState', { tabs: changeTabs })
  router.replace({ path: '/makeManage/autoScheduleLocal' })
}
const queryParams = (value) => {
  // console.log(value)
  recordInfo.value['lineId'] = makeDetailTable.value.baseData[0].lineId;
  recordInfo.value['remark'] = value.remark;
  recordInfo.value['staffIds'] = personList.value.map(item=>{return item.key})
  recordInfo.value['stationNos'] = stationList.value.map(item=>{return item.key})
  // console.log(operateProcList.value,'operateProcList.value.++++++++++++++++++')
  if (checkedProc.value){
    if (operateType.value === 'add'){
      recordInfo.value['autoRoadmapProcVO'] = {
        detailList:operateProcList.value.processInfoList || [],
        // id: operateProcList.value.autoRoadmapProcVO.id ?? '',
        name:operateProcList.value.autoRoadmapProcVO.name || '',
      }
    }else if(operateType.value === 'edit'){
      recordInfo.value['autoRoadmapProcVO']['detailList'] = operateProcList.value.processInfoList || []
      recordInfo.value['autoRoadmapProcVO']['name'] = operateProcList.value.autoRoadmapProcVO.name || version.value || ''
      console.log(operateProcList.value.autoRoadmapProcVO,'operateProcList.value.autoRoadmapProcVO-------------')
    }
  }
 /* makeDetailTable.value.initBoxData()
  console.log(makeDetailTable.value)
  let params = pick(value, ['moNo', 'workOrderNo', 'styleId', 'orderId', 'productDate', 'deliveryDate'])
  let tableData = makeDetailTable.value.boxData.map(item => {
    item
  })
  console.log(tableData)
  params.moDetailList = tableData
  params.productDate = params.productDate ? moment(params.productDate).valueOf() : null
  params.deliveryDate = params.deliveryDate ? moment(params.deliveryDate).valueOf() : null
  params.id = route.fullPath.includes('copy') ? null : recordInfo.value.id*/
  return recordInfo
}
const initFormData = async () => {
  let record = {}
  // console.log(recordInfo.value,'recordInfo.value-------------------------')
  if (recordInfo.value) {
    record = { ...recordInfo.value }
  }
  record.createTime = record.createTime ? moment(record.createTime).format('YYYY-MM-DD  HH:mm:ss') : moment(new Date()).format('YYYY-MM-DD  HH:mm:ss')
  await nextTick()
  formRef.value && formRef.value.resetFields()
  formState.value = cloneDeep(record)
  detailTableData.value = [{...formState.value}];
  // console.log(detailTableData.value,'detailTableData.value-------------------------------')
}
const initMethod = async () => {
  try {
    const resStaff = await axios.postAction('/api/basic/staff/list')
    if (resStaff.success) staffList.value = resStaff.data
    const resGroup = await axios.postAction('/api/basic/staff-group/list')
    if (resGroup.success) staffGroupList.value = resGroup.data
    let resLine = await axios.postAction('/api/device/hanger-line/list')
    if (resLine.success){  lineList.value = resLine.data; }

  }catch (err){
    console.log(err)
    closeTab()
  }



}
const getDetailInfo = async (id) => {
  try {
    const res = await axios.getAction('/api/mo/mo/get',{ id:id })
    // console.log(res)
    if (res.success) {
      let { id, moNo ,styleNo, productType, quantity, createTime } = res.data
      recordInfo.value = {
        autoRoadmapProcVO:{},
        lineId:null, moId:id, moNo:moNo, styleNo:styleNo, productType:productType, quantity:quantity,userNum:'', createTime:createTime,
        remark:'',
        staffIds:[],
        stationNos:[],
        status:Number,
        urlList:[],
      }
      // console.log(recordInfo.value)
    }
    let processListQuery = await axios.postAction('/api/mo/mo-proc/list',{moId:id})
    if (processListQuery.success){  processList.value = processListQuery.data }
    // console.log(processList.value,'processList.value ---------------')
  } catch {
    closeTab()
  }
}

const getEditDetailInfo = async (id) => {
  try {
    const res = await axios.getAction('/api/mo/auto-roadmap/get', {id:id} )
    if (res.success) {
      statusValue.value = res.data.status || 0
      recordInfo.value = res.data
      if (recordInfo.value.moId){
        const productInfo = await axios.getAction('/api/mo/mo/get', { id:recordInfo.value.moId })
        // console.log(productInfo,'productInfo--------------------')
        if (productInfo.success){
          recordInfo.value.moNo = productInfo.data.moNo
          recordInfo.value.styleNo = productInfo.data.styleNo
          recordInfo.value.productType = productInfo.data.productType
          recordInfo.value.quantity = productInfo.data.quantity
          recordInfo.value.userNum = recordInfo.value.staffIds.length
          recordInfo.value.createTime = productInfo.data.createTime
        }

        let processListQuery = await axios.postAction('/api/mo/mo-proc/list',{moId:recordInfo.value.moId})
        if (processListQuery.success){  processList.value = processListQuery.data }
        // console.log(processList.value,'processList.value ---------------')

        staffList.value && staffList.value.forEach(item=>{
          if (recordInfo.value.staffIds.includes(item.id)){
            personList.value.push( {title:item.staffNo+'-'+item.nickName,key:item.id})
          }
        })

        let lineNo = ''
        lineList.value && lineList.value.forEach(item=>{
          if (item.id===recordInfo.value.lineId){
            lineNo = item.lineNo
          }
        })
        recordInfo.value.stationNos && recordInfo.value.stationNos.forEach(item=>{
          stationList.value.push({title:lineNo+'-'+item,key:item})
        })
        // personList.value = recordInfo.value.staffIds
        // stationList.value = recordInfo.value.stationNos
      }
      // console.log(recordInfo.value,'recordInfo.value-------------------------')
      if (recordInfo.value.autoRoadmapProcVO){
        version.value = recordInfo.value.autoRoadmapProcVO.name || ''
        processInfoList.value = recordInfo.value.autoRoadmapProcVO.detailList
      }
      recordInfo.value.urlList && recordInfo.value.urlList.forEach((item,index)=>{
        fileList.value.push(
            {
              uid:index+1,
              name: item.split('/').slice(-1)[0],
              status: 'done',
              url:item
            }
        )
      })
      // console.log( fileList.value,' fileList.value---------------')
      // console.log(processInfoList.value)
    }
  } catch {
    closeTab()
  }
}

/* 上传 */
const handleImportExcel = (info) => {
  // console.log("info:::::", info)
  if (info.file.status !== 'uploading') {
    // console.log('uploading')
  }
  if (info.file.status === 'done') {
    if (info.file.response.success) {
      // message.success(`${info.file.name} 文件上传成功`)
    } else {
      message.error(info.file.response.msg)
    }
  } else if (info.file.status === 'error') {
    message.error(`${t('common.fileUploadErr')}: ${info.file.msg} `)
  }
}

onMounted(async () => {
  loading.value = true
  operateType.value = route.path === '/makeManage/addSchedule' ? 'add' : (route.path === '/makeManage/editSchedule/details'?'details': 'edit')
  // lookValue.value = route.path === '/makeManage/editSchedule/details'
  // console.log(route.query.id)
  if (operateType.value && !route.query.id) {
    // closeTab()
    console.log('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
    loading.value = false
    return
  }

   await initMethod()

  if (operateType.value === 'add'){
    await getDetailInfo(route.query.id)
  }else if(operateType.value === 'edit'){
    await getEditDetailInfo(route.query.id)
  }else if(operateType.value === 'details'){
    await getEditDetailInfo(route.query.id)
  }
  // await store.dispatch('getOrder')
  // await store.dispatch('getCustom')
  // await store.dispatch('getStyle')
  initFormData()
  loading.value = false
})
</script>
